package com.vehicle.ucenter.provider.serviceimpl;

import com.vehicle.ucenter.api.entity.SysMenu;
import com.vehicle.ucenter.api.entity.SysUser;
import com.vehicle.ucenter.api.service.SysMenuService;
import com.vehicle.ucenter.provider.mapper.SysMenuMapper;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yantingbin on 2017/7/10.
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> getAll() {
        return sysMenuMapper.findAllList();
    }

    @Override
    public List<SysMenu> getMenuNav(String userId) {
        return makeTree(getMenuListByUserId(userId),true);
    }

    private List<SysMenu> getMenuListByUserId(String userId) {
        List<SysMenu> menus;
        if (SysUser.ADMIN_USER_ID.equals(userId)) {
            menus = sysMenuMapper.findAllList();
        }else{
            menus=sysMenuMapper.findListByUserId(userId);
        }
        return menus;
    }

    private List<SysMenu> makeTree(List<SysMenu> originals, boolean useShow) {
        Map<String, SysMenu> dtoMap = new HashedMap();
        for (SysMenu node : originals) {
            String id = node.getId();
            if (node.getShow() || !useShow) {
                dtoMap.put(id, node);
            }
        }
        List<SysMenu> result = new ArrayList<>();

        for (Map.Entry<String, SysMenu> entry : dtoMap.entrySet()) {
            SysMenu node = entry.getValue();
            String parentId = node.getParentId();
            if (dtoMap.get(parentId) == null) {
                result.add(node);
            } else {
                SysMenu parent = dtoMap.get(parentId);
                parent.addChild(node);
                parent.setLeaf(false);
            }
        }

        return result;
    }
}
